package com.by.service.impl;


import com.by.bean.ShopCategory;
import com.by.common.core.crud.BaseServiceImpl;
import com.by.common.core.exception.BusinessException;
import com.by.mapper.ShopCategoryMapper;
import com.by.service.ShopCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShopCategoryServiceImpl extends BaseServiceImpl<ShopCategory, ShopCategoryMapper> implements ShopCategoryService {

    @Autowired
    ShopCategoryMapper shopCategoryMapper;

    /**
     * 一级分类添加
     * @param shopCategory
     * @return
     */
    @Override
    public int saveSCategoryOne(ShopCategory shopCategory) {
        //查询最大编码
        String code = shopCategoryMapper.queryMaxCode(0);
        String newCode="0"+(Integer.parseInt(code)+1);
        shopCategory.setCode(newCode);
        shopCategoryMapper.saveSCategoryOne(shopCategory);
        return 1;
    }
    /**
     * 子分类添加
     * @param shopCategory
     * @return
     */
    @Override
    public int saveSCategoryKids(ShopCategory shopCategory) {
        String maxCode = shopCategoryMapper.queryMaxCode(shopCategory.getParentid());
        if (null==maxCode){
            //最大编码为空 默认赋值父编码拼接01
            shopCategory.setCode(shopCategoryMapper.queryCodeById(shopCategory.getParentid())+"01");
        }else {
        //最大编码不为空 最大编码加一作为新编码
        int code=(Integer.parseInt(maxCode)+1);
        //新编码
        shopCategory.setCode("0"+code);
        System.out.println(shopCategory);}
        //添加新分类
        shopCategoryMapper.saveSCategoryKids(shopCategory);
        return 1;
    }

    /**
     * 类别树
     * @return
     */
    @Override
    public List<ShopCategory> categoryTree() {
       return shopCategoryMapper.categoryTree();
    }

    /**
     * 根据修改信息
     * @param id
     * @param name
     * @return
     */
    @Override
    public int updateSname(int id, String name) {
        return shopCategoryMapper.updateSname(id, name);
    }

    /**
     * 删除店铺分类
     * @param id
     * @return
     */
    @Override
    public int deleteShop(int id) {
        String code = shopCategoryMapper.queryCodeById(id);
        int i = shopCategoryMapper.haveKids(code);
       if (i>0){
           throw  new BusinessException("请先处理子类");
       }else {
           return shopCategoryMapper.deleteShop(id);
       }
    }
}
